package com.cskaoyan.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author stone
 * @date 2021/12/29 15:22
 */
@Configuration
@ComponentScan("com.cskaoyan")
//@PropertySource("classpath:param.properties")
@EnableAspectJAutoProxy       //要引入aspectjweaver依赖
@EnableTransactionManagement  //容器中要有TransactionManager组件
public class SpringConfig {


    //组件id：默认值 👉 方法名
    //       设定值 👉 @Bean注解的value属性值
    //@Bean // id = dataSource
    @Bean("druidDatasource") //id = druidDatasource
    public DruidDataSource dataSource() {
        //使用se代码风格提供实例
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/cskaoyan_db");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    //形参：从容器中按照类型取出组件（该类型组件在容器中只有一个）,如果该类型组件不止一个，需要指定组件id @Qualifier
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("druidDatasource") DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.cskaoyan.mapper");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}
